//
//  YSLoginViewController.m
//  Yaoyle
//
//  Created by ZhaoXudong on 14-9-15.
//  Copyright (c) 2014年 ZhaoXudong. All rights reserved.
//

#import "YSLoginViewController.h"
#import "YSRegViewController.h"
#import "YSCreateRoleViewController.h"
#import "YSUserModel.h"
#import "YSCreateDB.h"

@interface YSLoginViewController () <UITextFieldDelegate> {
    
    __weak IBOutlet UIImageView *checkBoxView;
    BOOL isRecordPsd;
}

@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;
@property (weak, nonatomic) IBOutlet UIScrollView *contentView;

@end

@implementation YSLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        isRecordPsd = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)loginBtnPress:(id)sender {
    
    NSString *phone = _phoneTextField.text;
    NSString *pwd = _pwdTextField.text;
    
    if (phone.length == 0 || [YSUtility isBlankObject:phone]) {
        [self showMsgWithTitle:@"提示" msg:@"注册手机号码不能为空"];
        return;
    }
    
    if (pwd.length == 0 || [YSUtility isBlankObject:pwd]) {
        [self showMsgWithTitle:@"提示" msg:@"密码不能为空"];
        return;
    }
    
    [YSProgressHUD showHUDAddedTo:self.view];
    [[NetworkMgr sharedManager] asynchRequestWithFunId:eAPI_LOGIN
                                              delegate:self
                                                params:@{@"mobile": phone,
                                                         @"password": pwd}];
}

- (IBAction)regNewAccount:(id)sender {
    YSRegViewController *regVC = [[YSRegViewController alloc] initWithNibName:@"YSRegViewController" bundle:nil];
    regVC.block = ^(NSDictionary *dict) {
        _phoneTextField.text = dict[RegPhoneKey];
        _pwdTextField.text = dict[RegPwdKey];
    };
    [self.navigationController pushViewController:regVC animated:YES];
}

- (IBAction)recordPsdClick:(id)sender {
    if (isRecordPsd) {
        isRecordPsd = NO;
        checkBoxView.image = [UIImage imageNamed:@"checkBox_no"];
    } else {
        isRecordPsd = YES;
        checkBoxView.image = [UIImage imageNamed:@"checkBox_yes"];
    }
}


#pragma mark - UITextFieldDelegate
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if (textField == _pwdTextField) {
        [_contentView setContentOffset:CGPointMake(0, 40) animated:YES];
    } else {
        [_contentView setContentOffset:CGPointMake(0, 16) animated:YES];
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [_contentView setContentOffset:CGPointMake(0, 0) animated:YES];
    [textField resignFirstResponder];
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == _phoneTextField && range.location >= 11) {
        return NO;
    }
    
    if (textField == _phoneTextField) {
        return [YSUtility validateNumber:string];
    }
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField == _phoneTextField) {
        FMResultSet *result = [YSCreateDB queryUser:_phoneTextField.text];
        if (result.next) {
            _pwdTextField.text = [result stringForColumn:@"password"];
        } else {
            _pwdTextField.text = @"";
        }
    }
    return YES;
}

#pragma mark - NetworkDelegate

- (void)didSuccess:(NetworkMgr *)api userInfo:(NSDictionary *)info {
    [YSProgressHUD hideHUDForView:self.view];
    
    NSInteger funId = [info[kFUN_ID] integerValue];
    NSDictionary *re = info[API_Result_RE];
    if ([YSUtility isBlankObject:re]) {
        return;
    }
    
    NSString *phone = _phoneTextField.text;
    NSString *pwd = _pwdTextField.text;
    
    FMResultSet *result = [YSCreateDB queryUser:phone];
    
    if (isRecordPsd) {
        // 更新数据库 -- 插入新用户
        if (!result.next) {
            [YSCreateDB insertUserInfo:phone andPwd:pwd];
        } else {
            [YSCreateDB updateUserInfo:phone andPwd:pwd];
        }
    } else {
        // 如果已经存在，删除数据库
        if (result.next) {
            [YSCreateDB deleteUser:phone];
        }
    }
    
    re = [YSUtility returnDictionary:re];
    if (funId == eAPI_LOGIN) {
        YSUserModel *userModel = [[YSUserModel alloc] initFromUserInfo:re];
        if ([userModel isHaveRole]) {
            if (self.block) {
                [userModel saveUserInfo];
                [self.navigationController popViewControllerAnimated:YES];
                _block(userModel);
            }
        } else {
            // 创建角色
            YSCreateRoleViewController *createRoleVC = [[YSCreateRoleViewController alloc] initWithNibName:@"YSCreateRoleViewController" bundle:nil];
            createRoleVC.block = ^(NSDictionary *dict) {
                userModel.name = dict[RoleName];
                userModel.sex = [dict[RoleSex] intValue];
                [userModel saveUserInfo];
                _block(userModel);
                [self.navigationController popViewControllerAnimated:YES];
            };
            [self.navigationController pushViewController:createRoleVC animated:YES];
        }
    }
}

@end
